#include "config.h"
#include "ui_config.h"

//创建一个串口类对象
QSerialPort *serial = new QSerialPort;
QSerialPort *serial_send = new QSerialPort;

network_confdef netconf;

QString filepath;

Config::Config(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Config)
{
    ui->setupUi(this);

    this->setWindowTitle("北斗上位机软件配置界面");
    setAttribute(Qt::WA_StyledBackground);
    ui->tabWidget->setTabText(0, tr("接收配置"));
    ui->tabWidget->setTabText(1, tr("发信配置"));

    socket = new QTcpSocket;

    //自动读取可用端口号
    QList<QSerialPortInfo> portlist = QSerialPortInfo::availablePorts();
    for(int i=0;i<portlist.size();i++)
    {
        ui->comboBox_serial->addItem(portlist.at(i).portName());
        ui->comboBox_serial_2->addItem(portlist.at(i).portName());
    }

    //建立串口波特率映射表
    baudrateMap["1200"] = QSerialPort::Baud1200;
    baudrateMap["2400"] = QSerialPort::Baud2400;
    baudrateMap["4800"] = QSerialPort::Baud4800;
    baudrateMap["9600"] = QSerialPort::Baud9600;
    baudrateMap["19200"] = QSerialPort::Baud19200;
    baudrateMap["38400"] = QSerialPort::Baud38400;
    baudrateMap["57600"] = QSerialPort::Baud57600;
    baudrateMap["115200"] = QSerialPort::Baud115200;

    //建立串口数据位映射表
    databitMap["8"] = QSerialPort::Data8;
    databitMap["7"] = QSerialPort::Data7;
    databitMap["6"] = QSerialPort::Data6;
    databitMap["5"] = QSerialPort::Data5;

    //建立串口停止位映射表
    stopbitMap["1"] = QSerialPort::OneStop;
    stopbitMap["1.5"] = QSerialPort::OneAndHalfStop;
    stopbitMap["2"] = QSerialPort::TwoStop;

    //建立串口奇偶校验位映射表
    parityMap["None"]= QSerialPort::NoParity;
    parityMap["Odd"]= QSerialPort::OddParity;
    parityMap["Even"]= QSerialPort::EvenParity;

    QSettings* conf_address = new QSettings("E:/QT/Project/BDSwork/configaddress.ini", QSettings::IniFormat);
    //E:/QT/Project/BDSwork/config.ini
    QString conf_location = conf_address->value("Address").toString();
    ui->configsave->setText(conf_location);
    delete  conf_address;
    //打开文件并指定为ini格式
    QSettings* configini = new QSettings(conf_location, QSettings::IniFormat);
    //读指定节点的指定数据


    //读取数据存储路径
    filepath = configini->value("Save/Filepath").toString();
    qDebug()<<filepath;
    ui->datasave->setText(filepath);

    //读取默认串口数据
    //读取配置文件中的端口号
    QString defaultconf_serial = configini->value("Receive/Serial/Port").toString();
    ui->comboBox_serial->setCurrentText(defaultconf_serial);

    //读取配置文件中的波特率
    QString defaultconf_baudrate = configini->value("Receive/Serial/Baudrate").toString();
    if(baudrateMap.contains(defaultconf_baudrate))
    {
        ui->comboBox_baudrate->setCurrentText(defaultconf_baudrate);
        serial->setBaudRate(baudrateMap[defaultconf_baudrate]);
    }
    //如果输入的波特率不在映射表中，则采用默认的115200
    else
    {
        ui->comboBox_baudrate->setCurrentText("115200");
        serial->setBaudRate(QSerialPort::Baud115200);
    }

    //读取配置文件中的数据位
    QString default_databitText = configini->value("Receive/Serial/DataBit").toString();
    ui->comboBox_databit->setCurrentText(default_databitText);
    if(parityMap.contains(default_databitText))
    {
        ui->comboBox_databit->setCurrentText(default_databitText);
        serial->setDataBits(databitMap[default_databitText]);
    }
    //如果输入的数据位不在映射表中，则采用默认的8
    else
    {
        ui->comboBox_databit->setCurrentText("8");
        serial->setDataBits(QSerialPort::Data8);
    }

    //读取配置文件中的停止位
    QString default_stopbitText = configini->value("Receive/Serial/StopBit").toString();
    if(stopbitMap.contains(default_stopbitText))
    {
        ui->comboBox_stopbit->setCurrentText(default_stopbitText);
        serial->setStopBits(stopbitMap[default_stopbitText]);
    }
    else
    {
        ui->comboBox_stopbit->setCurrentText("1");
        serial->setStopBits(QSerialPort::OneStop);
    }

    //读取配置文件中的奇偶校验位
    QString default_parityText = configini->value("Receive/Serial/Parity").toString();
    ui->comboBox_parity->setCurrentText(default_parityText);


    //读取配置文件中的端口号
    defaultconf_serial = configini->value("Send/Serial/Port").toString();
    ui->comboBox_serial_2->setCurrentText(defaultconf_serial);

    //读取配置文件中的波特率
    defaultconf_baudrate = configini->value("Send/Serial/Baudrate").toString();
    if(baudrateMap.contains(defaultconf_baudrate))
    {
        ui->comboBox_baudrate_2->setCurrentText(defaultconf_baudrate);
        serial_send->setBaudRate(baudrateMap[defaultconf_baudrate]);
    }
    //如果输入的波特率不在映射表中，则采用默认的115200
    else
    {
        ui->comboBox_baudrate_2->setCurrentText("115200");
        serial_send->setBaudRate(QSerialPort::Baud115200);
    }

    //读取配置文件中的数据位
    default_databitText = configini->value("Send/Serial/DataBit").toString();
    ui->comboBox_databit_2->setCurrentText(default_databitText);
    if(parityMap.contains(default_databitText))
    {
        ui->comboBox_databit_2->setCurrentText(default_databitText);
        serial_send->setDataBits(databitMap[default_databitText]);
    }
    //如果输入的数据位不在映射表中，则采用默认的8
    else
    {
        ui->comboBox_databit_2->setCurrentText("8");
        serial_send->setDataBits(QSerialPort::Data8);
    }

    //读取配置文件中的停止位
    default_stopbitText = configini->value("Send/Serial/StopBit").toString();
    if(stopbitMap.contains(default_stopbitText))
    {
        ui->comboBox_stopbit_2->setCurrentText(default_stopbitText);
        serial_send->setStopBits(stopbitMap[default_stopbitText]);
    }
    else
    {
        ui->comboBox_stopbit_2->setCurrentText("1");
        serial_send->setStopBits(QSerialPort::OneStop);
    }

    //读取配置文件中的奇偶校验位
    default_parityText = configini->value("Send/Serial/Parity").toString();
    ui->comboBox_parity_2->setCurrentText(default_parityText);


    //读取配置文件中的TCP接收相关配置
    QString default_rcv_tcp_ip = configini->value("Receive/Network/TCP_IP").toString();
    ui->rcv_tcp_ip->setText(default_rcv_tcp_ip);
    netconf.rcv_tcp_ip = default_rcv_tcp_ip;

    QString default_rcv_tcp_port = configini->value("Receive/Network/TCP_Port").toString();
    ui->rcv_tcp_port->setText(default_rcv_tcp_port);
    netconf.rcv_tcp_port = default_rcv_tcp_port;

    //读取配置文件中的TCP发送相关配置
    QString default_send_tcp_ip = configini->value("Send/Network/TCP_IP").toString();
    ui->tcp_ip->setText(default_send_tcp_ip);
    netconf.rcv_tcp_ip = default_send_tcp_ip;

    QString default_send_tcp_port = configini->value("Send/Network/TCP_Port").toString();
    ui->tcp_port->setText(default_send_tcp_port);
    netconf.rcv_tcp_port = default_send_tcp_port;

    //读取配置文件中UDP相关配置
    QString default_send_udp_ip = configini->value("Send/Network/UDP_IP").toString();
    ui->udp_ip->setText(default_send_udp_ip);
    netconf.send_udp_ip = default_send_udp_ip;

    QString default_send_udp_port = configini->value("Send/Network/UDP_Port").toString();
    ui->udp_port->setText(default_send_udp_port);
    netconf.send_udp_port = default_send_udp_port;

    //删除指针
    delete configini;
}

Config::~Config()
{
    delete ui;
}



void Config::on_detemineButton_clicked()
{
    //设置串口的端口
    serial->setPort(QSerialPortInfo(ui->comboBox_serial->currentText()));

    //设置端口的波特率
    QString baudrateText = ui->comboBox_baudrate->currentText();
    //如果输入的波特率在建立的映射表中，则采用输入的波特率
    if(baudrateMap.contains(baudrateText))
    {
        serial->setBaudRate(baudrateMap[baudrateText]);
    }
    //如果输入的波特率不在映射表中，则采用默认的115200
    else
    {
        serial->setBaudRate(QSerialPort::Baud115200);
    }

    //设置串口的数据位
    QString databitText = ui->comboBox_databit->currentText();
    if(databitMap.contains(databitText))
    {
        serial->setDataBits(databitMap[databitText]);
    }
    //如果输入的波特率不在映射表中，则采用默认的8
    else
    {
        serial->setDataBits(QSerialPort::Data8);
    }

    //4.设置串口的停止位
    QString stopbitText = ui->comboBox_stopbit->currentText();
    if(stopbitMap.contains(stopbitText))
    {
        serial->setStopBits(stopbitMap[stopbitText]);
    }
    else
    {
        serial->setStopBits(QSerialPort::OneStop);
    }

    //5.设置串口的奇偶校验位
    QString parityText = ui->comboBox_parity->currentText();
    if(parityText == "Odd")
    {
        serial->setParity(QSerialPort::OddParity);
    }
    else if(parityText == "Even")
    {
        serial->setParity(QSerialPort::EvenParity);
    }
    else
    {
        serial->setParity(QSerialPort::NoParity);
    }

    //设置串口的端口
    serial->setPort(QSerialPortInfo(ui->comboBox_serial->currentText()));

    //设置端口的波特率
    baudrateText = ui->comboBox_baudrate_2->currentText();
    //如果输入的波特率在建立的映射表中，则采用输入的波特率
    if(baudrateMap.contains(baudrateText))
    {
        serial_send->setBaudRate(baudrateMap[baudrateText]);
    }
    //如果输入的波特率不在映射表中，则采用默认的115200
    else
    {
        serial_send->setBaudRate(QSerialPort::Baud115200);
    }

    //设置串口的数据位
    databitText = ui->comboBox_databit_2->currentText();
    if(databitMap.contains(databitText))
    {
        serial_send->setDataBits(databitMap[databitText]);
    }
    //如果输入的波特率不在映射表中，则采用默认的8
    else
    {
        serial_send->setDataBits(QSerialPort::Data8);
    }

    //4.设置串口的停止位
    stopbitText = ui->comboBox_stopbit_2->currentText();
    if(stopbitMap.contains(stopbitText))
    {
        serial_send->setStopBits(stopbitMap[stopbitText]);
    }
    else
    {
        serial_send->setStopBits(QSerialPort::OneStop);
    }

    //5.设置串口的奇偶校验位
    parityText = ui->comboBox_parity_2->currentText();
    if(parityText == "Odd")
    {
        serial_send->setParity(QSerialPort::OddParity);
    }
    else if(parityText == "Even")
    {
        serial_send->setParity(QSerialPort::EvenParity);
    }
    else
    {
        serial_send->setParity(QSerialPort::NoParity);
    }

    //打开配置文件
    QSettings* configini = new QSettings("E:/QT/Project/BDSwork/config.ini", QSettings::IniFormat);

    //写入数据，必须指定写入节点和值
    //写入默认端口
    configini->setValue("Receive/Serial/Port", ui->comboBox_serial->currentText());

    //写入波特率
    configini->setValue("Receive/Serial/Baudrate", ui->comboBox_baudrate->currentText());

    //写入数据位
    configini->setValue("Receive/Serial/DataBit", ui->comboBox_databit->currentText());

    //写入停止位
    configini->setValue("Receive/Serial/StopBit", ui->comboBox_stopbit->currentText());

    //写入奇偶校验位
    configini->setValue("Receive/Serial/Parity", ui->comboBox_parity->currentText());

    //写入发信端口默认数据
    //写入默认端口
    configini->setValue("Send/Serial/Port", ui->comboBox_serial_2->currentText());

    //写入波特率
    configini->setValue("Send/Serial/Baudrate", ui->comboBox_baudrate_2->currentText());

    //写入数据位
    configini->setValue("Send/Serial/DataBit", ui->comboBox_databit_2->currentText());

    //写入停止位
    configini->setValue("Send/Serial/StopBit", ui->comboBox_stopbit_2->currentText());

    //写入奇偶校验位
    configini->setValue("Send/Serial/Parity", ui->comboBox_parity_2->currentText());

    //写入网口相关数据
    //读取当前设置的网口相关配置
    qDebug() << "Server IP:" << ui->tcp_ip->text();
    qDebug() << "Server Port:" << ui->tcp_port->text();
    qDebug() << "Client IP:" << ui->udp_ip->text();
    qDebug() << "Client Port:" << ui->udp_port->text();

    configini->setValue("Receive/Network/TCP_IP", ui->rcv_tcp_ip->text());
    netconf.rcv_tcp_ip = ui->rcv_tcp_ip->text();

    //
    configini->setValue("Receive/Network/TCP_Port", ui->rcv_tcp_port->text());
    netconf.rcv_tcp_port = ui->rcv_tcp_port->text();

    configini->setValue("Send/Network/TCP_IP", ui->tcp_ip->text());
    netconf.send_tcp_ip = ui->tcp_ip->text();

    //
    configini->setValue("Send/Network/TCP_Port", ui->tcp_port->text());
    netconf.send_tcp_port = ui->tcp_port->text();

    //
    configini->setValue("Send/Network/UDP_IP", ui->udp_ip->text());
    netconf.send_udp_ip = ui->udp_ip->text();

    //
    configini->setValue("Send/Network/UDP_Port", ui->udp_port->text());
    netconf.send_udp_port = ui->udp_port->text();


    //保存数据存储路径
    configini->setValue("Save/Filepath", ui->datasave->text());
    filepath = ui->datasave->text();

    //清除指针
    delete  configini;
    //
    QSettings* conf_address = new QSettings("E:/QT/Project/BDSwork/configaddress.ini", QSettings::IniFormat);
    //E:/QT/Project/BDSwork/config.ini
    conf_address->setValue("Address", ui->configsave->text());
    delete  conf_address;

    QMessageBox::information(this,"提示","设置已保存并应用成功！");

}


void Config::on_pingsever_clicked()
{
    netconf.rcv_tcp_ip = ui->rcv_tcp_ip->text();
    netconf.rcv_tcp_port = ui->rcv_tcp_port->text();

    //断开之前所有的槽
    disconnect(socket, &QTcpSocket::connected, nullptr, nullptr);
    disconnect(socket, &QTcpSocket::disconnected, nullptr, nullptr);
    disconnect(socket, &QTcpSocket::errorOccurred, nullptr, nullptr);

    socket->connectToHost(QHostAddress(netconf.rcv_tcp_ip),netconf.rcv_tcp_port.toShort());
    qDebug()<<"正在尝试连接目标地址:"<<netconf.rcv_tcp_ip<<":"<<netconf.rcv_tcp_port;
    connect(socket,&QTcpSocket::connected,[this]()
            {
                QMessageBox::information(this,"接收测试","连接服务器成功！");
    });

    connect(socket,&QTcpSocket::errorOccurred,[this]()
            {
                QMessageBox::warning(this,"接收测试","连接异常，请检查你的网口设置！");
            });
    socket->disconnectFromHost();
}


// void Config::on_pingclient_clicked()
// {
//     netconf.client_ip = ui->udp_ip->text();
//     tcpconf.client_port = ui->udp_port->text();
//     socket->connectToHost(QHostAddress(tcpconf.client_ip),tcpconf.client_port.toShort());
//     qDebug()<<"正在尝试连接目标地址:"<<tcpconf.client_ip<<":"<<tcpconf.client_port;
//     connect(socket,&QTcpSocket::connected,[this]()
//             {
//                 QMessageBox::information(this,"发送测试","连接目标端口成功！");
//             });

//     connect(socket,&QTcpSocket::errorOccurred,[this]()
//             {
//                 QMessageBox::warning(this,"发送测试","连接异常，请检查你的网口设置！");
//             });
//     socket->disconnectFromHost();
// }

